package com.sanjiayi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sanjiayi.mapper.LikeMapper;
import com.sanjiayi.mapper.MomentMapper;
import com.sanjiayi.pojo.Like;
import com.sanjiayi.pojo.Moment;
import com.sanjiayi.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private MomentMapper momentMapper;

    @Override
    @Transactional
    public boolean toggleLike(Integer userId, Integer momentId) {
        // 先检查动态是否存在
        Moment moment = momentMapper.selectById(momentId);
        if (moment == null) {
            throw new RuntimeException("动态不存在");
        }

        // 检查是否已点赞

        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("moment_id", momentId);
        Like existingLike = likeMapper.selectOne(queryWrapper);

        if (existingLike != null) {
            // 已点赞，取消点赞
            likeMapper.delete(queryWrapper);
            // 点赞数减1
            momentMapper.updateLikeCount(momentId, -1);
            return false;
        } else {
            // 未点赞，添加点赞
            Like like = new Like();
            like.setUserId(userId);
            like.setMomentId(momentId);
            like.setCreateTime(new Date());
            likeMapper.insert(like);
            // 点赞数加1
            momentMapper.updateLikeCount(momentId, 1);
            return true;
        }
    }

    @Override
    public boolean hasLiked(Integer userId, Integer momentId) {
        QueryWrapper<Like> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("moment_id", momentId);
        return likeMapper.selectCount(queryWrapper) > 0;
    }

    @Override
    public int getLikeCount(Integer momentId) {
        Integer count = momentMapper.getLikeCount(momentId);
        return count != null ? count : 0;
    }
} 